#!/usr/bin/env python3
# DATA: 2023/9/2
# author: 
#
import json
import os
import socket
import tkinter.filedialog
import requests
from tkinter import *


def send_selct_file():
    """ 发送文件 """
    if input1.get() == '':
        msg.config(text="请填写【目的地IP】")
    elif input2.get() == '':
        msg.config(text="您没有选择任何文件！")
    else:
        url = f"http://{input1.get().strip()}:8400/receive/file"
        with open(input2.get(), 'rb') as f:
            rsp = requests.post(url, files={'file': f})
            jsonrsp = json.loads(rsp.content)
        if jsonrsp['status'] == 'success':
            msg.config(text="文件发送成功！")
        else:
            msg.config(text="文件发送失败！")


def get_local_ip_address():
    """ 机器有多个IP是，获取ip"""
    countip = socket.getaddrinfo(socket.gethostname(), None, family=socket.AF_INET, proto=socket.IPPROTO_TCP)
    ipaddr = ""
    for i in range(len(countip)):
        ips = i, socket.getaddrinfo(socket.gethostname(), None, family=socket.AF_INET, proto=socket.IPPROTO_TCP)[i][4][
            0]
        if str(ips[1]).split(".")[-1] != '1':
            ipaddr = ips[1]
    return ipaddr


def select_file():
    """ 选择文件 """
    filepath = tkinter.filedialog.askopenfilename()
    if filepath != '':
        filename.set(filepath)
    else:
        msg.config(text="您没有选择任何文件！")


def open_files_dict():
    """ 打开files文件夹"""
    filespath = os.path.join(os.getcwd(), 'files')
    if os.path.exists(filespath) is False:
        os.makedirs(filespath)
    tkinter.filedialog.askopenfile(initialdir=os.path.join(os.getcwd(), 'files'))


window = Tk()
window.title("TransLAN")
window.geometry("600x300+500+300")
text0 = Label(window, text=f'本机IP:{get_local_ip_address()}', font=('宋体', 10))
text0.grid(row=0, column=1, pady=5)
text1 = Label(window, text='目的地IP：', font=('宋体', 10))
text1.grid(row=1, column=0, pady=20)
input1 = Entry(window, width=40)
input1.grid(row=1, column=1, pady=20)
rv = StringVar()
rv.set('win')
radio1 = Radiobutton(window, text='windows', variable=rv, value='win', font=('宋体', 10))
radio1.grid(row=1, column=2)
radio2 = Radiobutton(window, text='linux', variable=rv, value='lin', font=('宋体', 10))
radio2.grid(row=1, column=3)
text2 = Label(window, text="待发送文件：", font=('宋体', 10))
text2.grid(row=2, column=0, padx=10)
filename = StringVar()
input2 = Entry(window, width=40, textvariable=filename)
input2.grid(row=2, column=1)
button1 = Button(window, text="选 择", padx=5, background='#FFE4B5', width=10, font=('宋体', 12), relief=RAISED,
                 command=select_file)
button1.grid(row=2, column=2, padx=5)
button2 = Button(window, text='发 送...', pady=10, background='#FFD700', width=30, font=('宋体', 14),
                 command=send_selct_file)
button2.grid(row=3, column=1, pady=10)
msg = Label(window, text='', padx=5, font=('宋体', 12), justify='left')
msg.grid(row=4, column=1, pady=10)
button3 = Button(window, text='打开文件夹', width=10, background='#FFDEAD', command=open_files_dict)
button3.grid(row=4, column=2)

window.mainloop()
# #7CCD7C
